<template>
  <div class="provider-channel-config-add-edit">
    <a-card :title="isEdit ? '编辑服务商渠道配置' : '新增服务商渠道配置'">
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item label="服务商ID" name="providerId">
          <a-input-number
            v-model:value="formData.providerId"
            placeholder="请输入服务商ID"
            :min="1"
            style="width: 200px"
          />
        </a-form-item>

        <a-form-item label="渠道ID" name="channelId">
          <a-input-number
            v-model:value="formData.channelId"
            placeholder="请输入渠道ID"
            :min="1"
            style="width: 200px"
          />
        </a-form-item>

        <a-form-item label="环境类型" name="isSandbox">
          <a-radio-group v-model:value="formData.isSandbox">
            <a-radio :value="1">沙箱环境</a-radio>
            <a-radio :value="0">生产环境</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="基础配置" name="baseConfig">
          <div class="json-editor">
            <a-textarea
              v-model:value="baseConfigStr"
              placeholder="请输入基础配置(JSON格式)"
              :rows="8"
              @blur="validateJson('baseConfig')"
            />
            <div v-if="jsonErrors.baseConfig" class="json-error">
              {{ jsonErrors.baseConfig }}
            </div>
          </div>
        </a-form-item>

        <a-form-item label="费率配置" name="feeConfig">
          <div class="json-editor">
            <a-textarea
              v-model:value="feeConfigStr"
              placeholder="请输入费率配置(JSON格式)"
              :rows="6"
              @blur="validateJson('feeConfig')"
            />
            <div v-if="jsonErrors.feeConfig" class="json-error">
              {{ jsonErrors.feeConfig }}
            </div>
          </div>
        </a-form-item>

        <a-form-item label="扩展配置" name="extraConfig">
          <div class="json-editor">
            <a-textarea
              v-model:value="extraConfigStr"
              placeholder="请输入扩展配置(JSON格式)"
              :rows="6"
              @blur="validateJson('extraConfig')"
            />
            <div v-if="jsonErrors.extraConfig" class="json-error">
              {{ jsonErrors.extraConfig }}
            </div>
          </div>
        </a-form-item>

        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="formData.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 4, span: 20 }">
          <a-space>
            <a-button type="primary" @click="handleSubmit" :loading="submitting">
              {{ isEdit ? '更新' : '提交' }}
            </a-button>
            <a-button @click="handleCancel">取消</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter, useRoute } from 'vue-router';
import type { FormInstance } from 'ant-design-vue';
import type { ProviderChannelConfig } from './ProviderChannelConfig';
import {
  apiProviderChannelConfigAdd,
  apiProviderChannelConfigEdit,
  apiProviderChannelConfigFetchDetail
} from './api';

const router = useRouter();
const route = useRoute();
const formRef = ref<FormInstance>();

// 是否编辑模式
const isEdit = computed(() => !!route.params.id);
const configId = computed(() => Number(route.params.id));

// 表单数据
const formData = reactive<Partial<ProviderChannelConfig>>({
  providerId: undefined,
  channelId: undefined,
  isSandbox: 1,
  baseConfig: '',
  feeConfig: '',
  extraConfig: '',
  status: 1
});

// JSON字符串表示
const baseConfigStr = ref('');
const feeConfigStr = ref('');
const extraConfigStr = ref('');

// JSON验证错误
const jsonErrors = reactive({
  baseConfig: '',
  feeConfig: '',
  extraConfig: ''
});

// 提交状态
const submitting = ref(false);

// 表单验证规则
const rules = {
  providerId: [
    { required: true, message: '请输入服务商ID', type: 'number' }
  ],
  channelId: [
    { required: true, message: '请输入渠道ID', type: 'number' }
  ],
  isSandbox: [
    { required: true, message: '请选择环境类型' }
  ],
  status: [
    { required: true, message: '请选择状态' }
  ]
};

// 监听JSON字符串变化
watch([baseConfigStr, feeConfigStr, extraConfigStr], () => {
  formData.baseConfig = baseConfigStr.value;
  formData.feeConfig = feeConfigStr.value;
  formData.extraConfig = extraConfigStr.value;
});

// 验证JSON格式
const validateJson = (field: 'baseConfig' | 'feeConfig' | 'extraConfig') => {
  const value = field === 'baseConfig' ? baseConfigStr.value
                : field === 'feeConfig' ? feeConfigStr.value
                : extraConfigStr.value;

  if (!value.trim()) {
    jsonErrors[field] = '';
    return true;
  }

  try {
    JSON.parse(value);
    jsonErrors[field] = '';
    return true;
  } catch (error) {
    jsonErrors[field] = 'JSON格式错误';
    return false;
  }
};

// 格式化JSON
const formatJson = (jsonStr: string): string => {
  if (!jsonStr) return '';
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2);
  } catch {
    return jsonStr;
  }
};

// 获取配置详情
const fetchDetail = async () => {
  if (!isEdit.value) return;

  try {
    const response = await apiProviderChannelConfigFetchDetail(configId.value);

    if (response.success) {
      const data = response.data;
      Object.assign(formData, data);

      // 格式化显示JSON
      baseConfigStr.value = formatJson(data.baseConfig);
      feeConfigStr.value = formatJson(data.feeConfig);
      extraConfigStr.value = formatJson(data.extraConfig);
    } else {
      message.error(response.message || '获取配置详情失败');
      router.back();
    }
  } catch (error) {
    message.error('获取配置详情失败');
    console.error('获取配置详情失败:', error);
    router.back();
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
  } catch (error) {
    message.error('请检查表单填写');
    return;
  }

  // 验证所有JSON格式
  const jsonValid = ['baseConfig', 'feeConfig', 'extraConfig'].every(field =>
    validateJson(field as any)
  );

  if (!jsonValid) {
    message.error('请检查JSON格式');
    return;
  }

  submitting.value = true;

  try {
    const submitData = { ...formData };

    // 如果JSON字符串为空，设置为空对象
    if (!submitData.baseConfig?.trim()) submitData.baseConfig = '{}';
    if (!submitData.feeConfig?.trim()) submitData.feeConfig = '{}';
    if (!submitData.extraConfig?.trim()) submitData.extraConfig = '{}';

    const response = isEdit.value
      ? await apiProviderChannelConfigEdit(submitData as ProviderChannelConfig)
      : await apiProviderChannelConfigAdd(submitData as ProviderChannelConfig);

    if (response.success) {
      message.success(isEdit.value ? '更新成功' : '添加成功');
      router.push({ name: 'ProviderChannelConfigList' });
    } else {
      message.error(response.message || (isEdit.value ? '更新失败' : '添加失败'));
    }
  } catch (error) {
    message.error(isEdit.value ? '更新失败' : '添加失败');
    console.error('提交失败:', error);
  } finally {
    submitting.value = false;
  }
};

// 取消
const handleCancel = () => {
  router.back();
};

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields();
  baseConfigStr.value = '';
  feeConfigStr.value = '';
  extraConfigStr.value = '';
  Object.assign(jsonErrors, {
    baseConfig: '',
    feeConfig: '',
    extraConfig: ''
  });
};

onMounted(() => {
  fetchDetail();
});
</script>

<style scoped>
.provider-channel-config-add-edit {
  padding: 20px;
}

.json-editor {
  position: relative;
}

.json-error {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.ant-card {
  max-width: 800px;
}
</style>